package cn.uikit.demo.recyclerview

import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import cn.uikit.demo.databinding.FragmentRecyclerViewBinding
import cn.uikit.demo.databinding.ItemRvGridLayoutBinding
import sivin.uikit.adapter2.SimpleAdapter
import sivin.uikit.adapter2.XViewHolder
import sivin.uikit.framework.BindingFragment
import sivin.uikit.utils.dp

class GridFragment : BindingFragment<FragmentRecyclerViewBinding>(
    FragmentRecyclerViewBinding::inflate
) {

    private val rvAdapter = SimpleAdapter<String, ItemRvGridLayoutBinding>(
        ItemRvGridLayoutBinding::inflate
    ) { holder, _, position ->
        // 根据 position 设置高度，如果是第一个 item，并且数量为奇数，则设置高度跨两行
        if (position == 0 && dataList.size % 2 != 0) {
            val params = holder.itemView.layoutParams
            params.height = 150f.dp
            holder.itemView.layoutParams = params
        } else {
            // 默认高度
            val params = holder.itemView.layoutParams
            params.height = 75f.dp
            holder.itemView.layoutParams = params
        }
    }

    private val mLayoutManager by lazy {
        val gridLayoutManager = StaggeredGridLayoutManager(2, RecyclerView.VERTICAL)
        gridLayoutManager
    }

    private val dataList = arrayListOf("测试1", "测试2", "测试3", "测试4", "测试5")

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.rv.apply {
            adapter = rvAdapter
            layoutManager = mLayoutManager
            addItemDecoration(SpaceItemDecoration())
        }
        rvAdapter.setDataList(dataList)
    }

    class SpaceItemDecoration : ItemDecoration() {
        private val left = 8f.dp
        private val bottom = 8f.dp
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            outRect.bottom = bottom
            outRect.left = left
        }
    }
}